package com.wing.productionPlan.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.enums.Idempotent;
import com.wing.common.enums.MaintenanceEnum;
import com.wing.enterprise.feign.EnterpriseClient;
import com.wing.productionPlan.model.entity.ProductionPlan;
import com.wing.productionPlan.model.request.DeviceTypeForm;
import com.wing.productionPlan.model.request.SubmitProductionPlanForm;
import com.wing.productionPlan.model.response.*;
import com.wing.productionPlan.service.ProductionProcessService;
import com.wing.productionPlan.service.ProductionTheWorkOrderService;
import com.wing.qualityTesting.model.request.QualityTestingRecordForm;
import com.wing.qualityTesting.model.request.WorkOrderQualityTestingTaskForm;
import com.wing.qualityTesting.service.QualityTestingRecordService;
import com.wing.qualityTesting.service.WorkOrderQualityTestingTaskService;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.productionPlan.model.entity.ProductionWorkOrder;
import com.wing.productionPlan.model.request.ProductionWorkOrderForm;
import com.wing.productionPlan.service.ProductionWorkOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author
 */
@Slf4j
@Validated
@Api(value = "Admin-生产开工单管理", tags = "#/productionPlan/productionWorkOrder")
@RestController("productionWorkOrderController")
@RequestMapping("productionPlan/admin/productionWorkOrder")
@RequiredArgsConstructor
public class ProductionWorkOrderController {

    private final ProductionWorkOrderService productionWorkOrderService;
    private final WorkOrderQualityTestingTaskService workOrderQualityTestingTaskService;
    private final ProductionProcessService productionProcessService;

    @Autowired
    private ProductionTheWorkOrderService productionTheWorkOrderService;

    @ApiOperation(value = "查询所有生产开工单", notes = "搜索")
    @GetMapping("/list")
    public PageResult<ProductionWorkOrderVO> list(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer limit,
            @RequestParam(defaultValue = "create_time") String sort,
            @RequestParam(defaultValue = "asc") String order,
            ProductionWorkOrderVO productionWorkOrderVO) {
        IPage<ProductionWorkOrderVO> pageList = productionWorkOrderService.getProductionWorkOrderVOPageList(productionWorkOrderVO, page, limit);
        List<ProductionWorkOrderVO> records = pageList.getRecords();

        //记录2
        if (CollectionUtil.isNotEmpty(records)){
            for (ProductionWorkOrderVO orderVO : records) {
                orderVO.setProcessTypeName(MaintenanceEnum.gxTypeEmum.getNameByCode(orderVO.getProcessType()));
                if (StrUtil.isNotEmpty(orderVO.getDeviceTypes())) {
                    List<String> strings = Arrays.asList(orderVO.getDeviceTypes().split(","));
                    List<DeviceOrWorkVo> fessionlist = productionProcessService.fessionlist(strings);
                    List<DeviceOrWorkVo> devicelist = productionProcessService.devicelist(strings);
                    if (CollectionUtil.isNotEmpty(devicelist)) {
                        List<String> collect1 = devicelist.stream().map(DeviceOrWorkVo::getDeviceName).collect(Collectors.toList());
                        String collected = String.join(",", collect1);
                        orderVO.setDeviceTypeNames(collected);
                    } else if (CollectionUtil.isNotEmpty(fessionlist)) {
                        List<String> collect1 = fessionlist.stream().map(DeviceOrWorkVo::getDeviceName).collect(Collectors.toList());
                        String collected = String.join(",", collect1);
                        orderVO.setDeviceTypeNames(collected);
                    }
                }
                WorkOrderSendTotallVO workOrderSendTotallVO = this.productionTheWorkOrderService.getTotalBy(orderVO.getId());
                if (ObjectUtil.isNotEmpty(workOrderSendTotallVO)) {
                    orderVO.setWorkQuantityTotal(workOrderSendTotallVO.getWorkQuantityTotal());
                    orderVO.setSendQuantityTotal(workOrderSendTotallVO.getSendQuantityTotal());
                    orderVO.setAcceptanceQuantity(workOrderSendTotallVO.getWorkQuantityTotal()-orderVO.getAcceptanceNoQuantity());
                    //样品检测合格率
                    Integer workQuantityTotal = workOrderSendTotallVO.getWorkQuantityTotal();
                    if (workQuantityTotal > 0) {
                        //报工数 - 不合格数 = 合格数 (分子)
                        BigDecimal numeratorBd = new BigDecimal(workOrderSendTotallVO.getWorkQuantityTotal() - orderVO.getAcceptanceNoQuantity());

                        //报工数 分母
                        BigDecimal workQuantity = new BigDecimal(workOrderSendTotallVO.getWorkQuantityTotal());
                        // 执行除法，保留两位小数，使用四舍五入
                        BigDecimal percentage = numeratorBd.divide(workQuantity, 4, RoundingMode.HALF_UP).multiply(new BigDecimal(100));
                        // 设置保留两位小数
                        BigDecimal result = percentage.setScale(2, RoundingMode.HALF_UP);
                        orderVO.setBgOkRate(result);

                    } else {
                        orderVO.setBgOkRate(new BigDecimal("100"));
                    }
                    //报工合格率
                    Integer sendQuantityTotal = workOrderSendTotallVO.getSendQuantityTotal();
                    if (sendQuantityTotal > 0) {
                        //送检数 - 不合格数 (分母)
                        BigDecimal numeratorBd = new BigDecimal(sendQuantityTotal - orderVO.getAcceptanceNoQuantity());
                        //合格数
                        BigDecimal okA = new BigDecimal(workOrderSendTotallVO.getSendQuantityTotal() - orderVO.getAcceptanceNoQuantity());

                        // 执行除法，保留两位小数，使用四舍五入
                        BigDecimal percentage = okA.divide(numeratorBd, 4, RoundingMode.HALF_UP).multiply(new BigDecimal(100));
                        // 设置保留两位小数
                        BigDecimal result = percentage.setScale(2, RoundingMode.HALF_UP);
                        orderVO.setYpOkRate(result);

                    } else {
                        orderVO.setYpOkRate(new BigDecimal("100"));
                    }
                }

                if (ObjectUtil.isNotEmpty(productionWorkOrderVO.getProductionPlanRecordId())){
                    records = records.stream().sorted(Comparator.comparing(ProductionWorkOrderVO::getProcessId)).collect(Collectors.toList());
                    pageList.setRecords(records);
                }
            }

        }
        return new PageResult<>(pageList.getRecords(), pageList.getTotal());
    }

    @ApiOperation(value = "添加开工单", notes = "添加")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "productionWorkOrderForm", value = "添加生产开工单数据", dataType = "Object", paramType = "query")
    })
    @Idempotent(keyPrefix = "workOrderSubmit")
    @PostMapping("/submitWorkOrder")
    public JsonResult submitWorkOrder(@RequestBody ProductionWorkOrderForm productionWorkOrderForm) {
        try {
            productionWorkOrderService.submitWorkOrder(productionWorkOrderForm);
            return JsonResult.success("操作成功");
        } catch (Exception e) {
            log.error("submitWorkOrder接口异常，原因是：{} ", e.getMessage(), e);
            return JsonResult.fail("操作失败:" + e.getMessage());
        }
    }

    @ApiOperation(value = "选择开工单(下拉框使用)", notes = "搜索")
    @GetMapping("/getAllWorkOrder")
    public JsonResult<List<ProductionWorkOrder>> getAllWorkOrder() {
        QueryWrapper<ProductionWorkOrder> wrapper = new QueryWrapper<>();
        wrapper.select("id", "code");
        List<ProductionWorkOrder> list = productionWorkOrderService.list(wrapper);
        return JsonResult.success(list);
    }

    @ApiOperation(value = "开工单信息和工序信息", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "workOrderId", value = "开工单id", dataType = "Long", paramType = "query")
    })
    @GetMapping("/getWorkOrderDetails")
    public JsonResult<ProductionWorkOrderVO> getWorkOrderDetails(Long workOrderId,String workOrderCode) {
        ProductionWorkOrderVO workOrderVO = productionWorkOrderService.getWorkOrderDetails(workOrderId,workOrderCode);
        return JsonResult.success(workOrderVO);
    }

    @ApiOperation(value = "", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    @Idempotent(keyPrefix = "workOrderAdd")
    public JsonResult add(@Validated(ProductionWorkOrderForm.Add.class) ProductionWorkOrderForm productionWorkOrderForm) {
        if (productionWorkOrderService.add(productionWorkOrderForm) > 0) {
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }


    @ApiOperation(value = "修改生产开工单", notes = "修改")
    @PostMapping("/update")
    @Idempotent(keyPrefix = "workOrderUpdate")
    public JsonResult update(@Validated(ProductionWorkOrderForm.Update.class) ProductionWorkOrderForm productionWorkOrderForm) {
        ProductionWorkOrder productionWorkOrder = productionWorkOrderService.getById(productionWorkOrderForm.getId());
        if (productionWorkOrder == null) {
            return JsonResult.fail("修改失败！");
        }
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(ProductionWorkOrder.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(productionWorkOrderForm, productionWorkOrder, copyOptions);
        if (productionWorkOrderService.updateById(productionWorkOrder)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }


    @ApiOperation(value = "删除生产开工单", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "productionWorkOrderId", value = "生产开工单id", required = true, dataType = "Integer", paramType = "path")
    })
    @DeleteMapping("/{id}")
    public JsonResult delete(@PathVariable("id") Long productionWorkOrderId) {
        if (productionWorkOrderService.removeById(productionWorkOrderId)) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }

    @ApiOperation(value = "添加首件检测", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/addFirstTask")
    public JsonResult addFirstTask(@RequestBody WorkOrderQualityTestingTaskForm workOrderQualityTestingTaskForm) {
        try {
            int add = workOrderQualityTestingTaskService.add(workOrderQualityTestingTaskForm, "2");
            if ( add > 0) {
                if (add == 2) {
                    return JsonResult.fail("添加失败 送检数不能大于剩余可送检数!");
                }
                return JsonResult.success("添加成功");
            }
            return JsonResult.success("操作成功");
        }catch (Exception e){
            log.error("提交质检记录接口异常，原因是：{} ", e.getMessage(), e);
            return JsonResult.fail("操作失败:" + e.getMessage());
        }
    }

    @ApiOperation(value = "工单详情",notes = "工单-详情")
    @GetMapping("/detail/{orderId}")
    public JsonResult<ProductionWorkOrderDetailVO> detail(@PathVariable("orderId") Long orderId) {
        ProductionWorkOrderDetailVO byId = productionWorkOrderService.getDetailBy(orderId);
        return JsonResult.success(byId);
    }


    @ApiOperation(value = "查询开工单(上一道工序的)",notes = "开工单-上一道")
    @GetMapping("/getUpOneInfo/{orderId}")
    public JsonResult<Map<String,Object>> getUpOneInfo(@PathVariable("orderId") Long orderId) {
        Map<String,Object> byId = productionWorkOrderService.getUpOneInfo(orderId);
        return JsonResult.success(byId);
    }

    @ApiOperation(value = "查询工序流程卡信息",notes = "工序流程卡")
    @GetMapping("/getProcessCardBy/{id}")
    public JsonResult<Map<String,Object>> getProcessCardBy(@PathVariable("id") Long id) {
        ProcessCardInfoVo byId = productionWorkOrderService.getProcessCardBy(id);
        return JsonResult.success(byId);
    }


    @ApiOperation(value = "查询工序开工单信息(打印)",notes = "工序开工单信息(打印)")
    @GetMapping("/getWorkOrderPrint/{id}")
    public JsonResult<Map<String,Object>> getWorkOrderPrint(@PathVariable("id") Long id) {
        ProWorkOrderPrintVo byId = productionWorkOrderService.getWorkOrderPrint(id);
        return JsonResult.success(byId);
    }

}
